﻿using DataServer.CommonLib.Models.DataConfig;
using Newtonsoft.Json;

namespace DataServer.ApplicationLib.Controls
{
    public class ControlSelect : ControlBase
    {
        public ControlSelectModel? Data { get; private set; }

        public override void BuildEditDefineValue(ConfigFieldInfoResponseDto configFieldInfoDto)
        {
            if (Data != null)
            {
                configFieldInfoDto.DataSourceTypeSelect = Data.DataSourceType;
                configFieldInfoDto.DataSourceValueSelect = Data.DataSourceValue;
                configFieldInfoDto.DataSourceTextSelect = Data.DataSourceText;
                configFieldInfoDto.DataSourceStaticValueSelect = Data.DataSourceStaticValue;
            }
        }

        public override ControlBase Deserialize(string controlContent)
        {
            if (!string.IsNullOrEmpty(controlContent))
                Data = JsonConvert.DeserializeObject<ControlSelectModel>(controlContent);
            return this;
        }

        public override string Serialize()
        {
            if (Data != null)
            {
                return JsonConvert.SerializeObject(Data);
            }
            return string.Empty;
        }

        public override Tuple<bool, string, ControlBase> TryValidationCreatorControl(ConfigFieldEditRequestDto model)
        {
            var textBoxModel = new ControlSelectModel
            {
                ControlName = model.ControlType,
                DataSourceType = model.DataSourceTypeSelect,
                DataSourceValue = model.DataSourceValueSelect,
                DataSourceText = model.DataSourceTextSelect,
                DataSourceStaticValue = model.DataSourceStaticValueSelect
            };

            var controlBase = new ControlSelect
            {
                Data = textBoxModel
            };

            return new Tuple<bool, string, ControlBase>(true, string.Empty, controlBase);
        }
    }

    public class ControlSelectModel
    {
        public string ControlName { get; set; }

        public string? DataSourceType { get; set; }

        public string? DataSourceValue { get; set; }

        public string? DataSourceText { get; set; }

        public IList<ConfigStaticValueModelDto> DataSourceStaticValue { get; set; }
    }
}
